<template>
	<view class="pageview">
		<cl-navbar autoBack placeholder  :title="$t('chat.groupChatDetails.title')"></cl-navbar>
		<view class="pageContent">
			<template v-if="groupInfo && groupInfo.mygroup == '1'">
				<view class="centerTop" @click="goEditInfo">
					<view class="centerTop__view">
						<view class="centerTop__view__topview">
							<cl-avatar
								:src="groupInfo.avatar_url"
								size="140rpx" preview></cl-avatar>
							<view class="centerTop__view__topview__info">
								<view style="display: flex;align-items: center;">
									<text class="centerTop__view__topview__info__nickname">{{groupInfo.group_name}}</text>
								</view>
								<view style="display: flex;align-items: center;margin-top: 10rpx;" @click.stop="copy">
									<text class="centerTop__view__topview__info__account">{{$t("chat.groupChatDetails.group_no")}}：{{groupInfo.g_no}}</text>
									<u-icon name="file-text" size="15px"></u-icon>
								</view>
							</view>
						</view>
						<u-icon name="arrow-right" color="#ffffff" size="20px" style="margin-right: 20rpx;" v-if="groupInfo.userRole == 'creator' || groupInfo.userRole == 'manager'"></u-icon>
					</view>
					<view class="centerTop__signature u-line-3">
						{{$t('chat.groupChatDetails.description')}}：<span style="color: #ffffff;">{{groupInfo.description || $t("chat.groupChatDetails.nodescription")}}</span> 
					</view>
				</view>
				<view class="topInfo">
					<view class="topInfo__numview" @click="allMember">
						<text>{{$t("chat.groupChatDetails.groupMember")}}</text>
						<view class="topInfo__numview__right">
							<text class="topInfo__numview__right__num">{{$t("chat.groupChatDetails.groupMember")}}{{memberTotal}}{{$t("chat.groupChatDetails.people")}}</text>
							<u-icon name="arrow-right" color="#ffffff"></u-icon>
						</view>
					</view>
					<view class="topInfo__view">
						<view class="topInfo__view__item" v-for="(item,index) in getMemberSee" :key="index" @click="memberDel(item)">
							<cl-avatar :src="item.avatar_url" size="100rpx"></cl-avatar>
							<text class="topInfo__view__item__nickname u-line-1">{{item.group_nickname || item.user_nickname}}</text>
						</view>
						<view class="topInfo__view__item" @click="invite" v-if="getPermission('is_invitation')">
							<view style="width: 100rpx;height: 100rpx;align-items: center;justify-content: center;display: flex;">
								<image src="/static/icon/add.png" style="width: 64rpx;height: 64rpx;"></image>
							</view>
							<text class="topInfo__view__item__nickname u-line-1">{{$t("chat.groupChatDetails.InviteFriends")}}</text>
						</view>
						<view class="topInfo__view__item" @click="remove" v-if="groupInfo.userRole == 'creator' || groupInfo.userRole == 'manager'">
							<view style="width: 100rpx;height: 100rpx;align-items: center;justify-content: center;display: flex;">
								<image src="/static/icon/sum.png" style="width: 64rpx;height: 64rpx;"></image>
							</view>
							<text class="topInfo__view__item__nickname u-line-1">{{$t("chat.groupChatDetails.Remove")}}</text>
						</view>
					</view>
				</view>
			</template>
			<view class="cellviewGrop" @click="popNameOpen">
				<view class="cellview">
					<view class="cellview__left">
						<text class="cellview__left__title">{{$t("chat.groupChatDetails.inGroupNickname")}}</text>
					</view>
					<view class="cellview__right">
						<text class="cellview__right__content">{{groupInfo.userNickname || user_info.nick_name}}</text>
						<u-icon name="arrow-right" color="#ffffff"></u-icon>
					</view>
				</view>
			</view>
			<view class="cellviewGrop" @click="historyChat">
				<view class="cellview">
					<view class="cellview__left">
						<text class="cellview__left__title">{{$t("friendChatDetails.searchChatHistory")}}</text>
					</view>
					<view class="cellview__right">
						<text class="cellview__right__content">{{$t("friendChatDetails.searchChatHistoryType")}}</text>
						<u-icon name="arrow-right" color="#ffffff"></u-icon>
					</view>
				</view>
			</view>
			<template  v-if="groupInfo && groupInfo.mygroup == '1'">
				<view class="cellviewGrop" @click="editInfo('notice','textarea',$t('chat.groupChatDetails.notice'))">
					<view class="cellview">
						<view class="cellview__left">
							<text class="cellview__left__title">{{$t('chat.groupChatDetails.notice')}}</text>
						</view>
						<view class="cellview__right">
							<u-icon name="arrow-right" color="#ffffff"></u-icon>
						</view>
					</view>
					<view class="cellDetails u-line-3">
						{{groupInfo.notice || '--'}}
					</view>
				</view>
				<view class="cellviewGrop" @click="gopage('group_chat_manage')" v-if="groupInfo.userRole == 'creator' || groupInfo.userRole == 'manager'">
					<view class="cellview">
						<view class="cellview__left">
							<text class="cellview__left__title">{{$t("chat.group_chat_config.title")}}</text>
						</view>
						<view class="cellview__right">
							<text class="cellview__right__content">{{$t("chat.groupChatDetails.GroupManagementDesc")}}</text>
							<u-icon name="arrow-right" color="#ffffff"></u-icon>
						</view>
					</view>
				</view>
			</template>
			<view class="cellviewGrop">
				<view class="cellview">
					<view class="cellview__left">
						<text class="cellview__left__title">{{$t("chat.groupChatDetails.MsgNotDisturb")}}</text>
					</view>
					<view class="cellview__right">
						<u-switch :value="groupInfo.disturbing" @change="e=>setChange('disturbing',e)" size="20" :activeValue="1" :inactiveValue="0" inactiveColor="#121325" activeColor="#121325"></u-switch>
					</view>
				</view>
			</view>
			<view class="cellviewGrop">
				<view class="cellview">
					<view class="cellview__left">
						<text class="cellview__left__title">{{$t("chat.groupChatDetails.topChat")}}</text>
					</view>
					<view class="cellview__right">
						<u-switch v-model="is_top" @change="e=>setChange('pinned',e)" size="20" :activeValue="1" :inactiveValue="0" inactiveColor="#121325" activeColor="#121325"></u-switch>
					</view>
				</view>
			</view>
			
			<view class="cellviewGrop" @click="gopage('report')">
				<view class="cellview">
					<view class="cellview__left">
						<text class="cellview__left__title">{{$t("friendChatDetails.report")}}</text>
					</view>
					<view class="cellview__right">
						<u-icon name="arrow-right" color="#ffffff"></u-icon>
					</view>
				</view>
			</view>
			
			<view class="controlsBotton" @click="clearchat">
				<text class="cellview__left__title" style="color: #61afef;">{{$t("my_file.setting.index.clearChatHistory")}}</text>
			</view>
			
			
			
			<view class="controlsBotton" @click="quitclick(groupInfo.userRole)" v-if="groupInfo && groupInfo.mygroup == '1' && getPermission('can_quit_range')">
				<text class="cellview__left__title" v-if="groupInfo && groupInfo.mygroup == '1'">{{groupInfo.userRole == 'creator'?$t('chat.groupChatDetails.dissolve'):$t('chat.groupChatDetails.quit')}}</text>
			</view>
			<view class="controlsBotton" @click="deleteClick" v-if="groupInfo && groupInfo.mygroup == '0'">
				<text class="cellview__left__title" v-if="groupInfo && groupInfo.mygroup == '0'">{{$t("common.deleteText")}}</text>
			</view>
		</view>
		<view>
			<cl-model ref="clmodel"></cl-model>
			<cl-edit-pop ref="clEditPop" :title="editInfoData.title" @complete="popComplete" @cancel="popCancel" :right="groupInfo.userRole == 'creator' || groupInfo.userRole == 'manager'">
				<view style="padding:30rpx;" >
					<u-input
						v-if="editInfoData.type=='input'"
						:customStyle="{backgroundColor:'#1E1F30',height:'110rpx',padding:'0 30rpx',borderRadius: '20rpx'}"
						fontSize="28rpx"
						color="#ffffff"
						focus
						:adjustPosition="false"
					    border="none"
						v-model="editInfoData.data[editInfoData.model]"
					  ></u-input>
					 <u-textarea :maxlength="-1" :focus="groupInfo.userRole == 'creator' || groupInfo.userRole == 'manager'" :disabled = "groupInfo.userRole != 'creator' && groupInfo.userRole != 'manager'" autoHeight  v-model="editInfoData.data[editInfoData.model]" border="none" :customStyle="{backgroundColor:'#1E1F30'}" :adjustPosition="false" v-if="editInfoData.type=='textarea'"></u-textarea>
				</view>
			</cl-edit-pop>
			
			<cl-edit-pop ref="clEditNamePop" :title="$t('chat.groupChatDetails.inGroupNickname')" @complete="popNameComplete" @cancel="popNameCancel">
				<view style="padding:30rpx;" >
					<u-input
						:customStyle="{backgroundColor:'#1E1F30',height:'110rpx',padding:'0 30rpx',borderRadius: '20rpx'}"
						fontSize="28rpx"
						color="#ffffff"
						focus
						:adjustPosition="false"
					    border="none"
						v-model="myGroupName"
					  ></u-input>
				</view>
			</cl-edit-pop>
		</view>
	</view>
</template>

<script>
	import sqliteGroup from '@/sqlite_services/group.js'
	import sqliteSeesion from '@/sqlite_services/seesion.js'
	import upload from '@/common/upload/upload.js'
	import groupApi from '@/services/api/group.js'
	import groupMembersApi from '@/services/api/group_members.js'
	import msgSqlite from "@/sqlite_services/msg.js"
	import {
		mapState
	} from 'vuex'
	
	// 定义排序规则的映射
	const roleOrder = {
	  'creator': 0,
	  'manager': 1,
	  'member': 2
	};
	
	export default {
		name: 'group_chat_details',
		data() {
			return {
				group_id:0,
				is_top:0,
				editInfoData:{
					type:'',
					title:'',
					model:'',
					data:{}
				},
				memberList:[],
				memberTotal:0,
				myGroupName:'',//我在群内的昵称
			}
		},
		computed: {
			...mapState({
				groupInfo: state => state.chat.chatGroupInfo,
				user_info: state => state.user.user_info,
			}),
			getPermission(){
				return (type)=>{
					if(this.groupInfo == null)return false
					// 0所有人 1普通用户 2管理员 3都不允许
					if(this.groupInfo[type] == '0'){
						return true
					}else if(this.groupInfo[type] == '1'){
						if(this.groupInfo.userRole && this.groupInfo.userRole != 'manager')return true
					}else if(this.groupInfo[type] == '2'){
						if(this.groupInfo.userRole && this.groupInfo.userRole != 'member')return true
					}else if(this.groupInfo[type] == '3'){
						if(this.groupInfo.userRole && this.groupInfo.userRole == 'creator')return true
					}
					return false
				}
			},
			//群成员可以显示的数组
			getMemberSee(){
				let members = JSON.parse(JSON.stringify(this.memberList))
				members.sort((a, b) => {
				  return roleOrder[a.role] - roleOrder[b.role];
				});
				let count = 10
				if(this.groupInfo.userRole == 'creator' || this.groupInfo.userRole == 'manager'){
					count --
				}
				if(this.getPermission('is_invitation')){
					count --
				}
				return members.slice(0, count)
			},
		},
		watch:{
			"groupInfo.mygroup": {
			  handler(newVal,oldVal) {
				 if(newVal == 1){
					 this.getMember()
				 }
			  },
			  deep: true,
			  immediate:true
			}
		},
		async onLoad() {
			this.gettop()
			uni.$on('onGroupMemberAction',this.onGroupMemberAction)
		},
		onUnload() {
			uni.$off('onGroupMemberAction', this.onGroupMemberAction);
		},
		methods: {
			copy(){
				console.log(this.groupInfo.g_no);
				uni.setClipboardData({
					data:this.groupInfo.g_no+'',
					showToast:false,
					success: () => {
						uni.showToast({
							icon:'none',
							title:this.$t("tost.title.copyOk")
						})
					}
				});
			},
			//监听群成员变化
			onGroupMemberAction(data){
				if(data.type == 'userInfo'){
					let index = this.memberList.findIndex(item => item.user_id == data.data.user_id);
					if (index !== -1) {
					  for (let key in data.data) {
					    if (data.data[key] != this.memberList[index][key]) {
					      Vue.set(this.memberList[index], key, data.data[key]);
					    }
					  }
					}
				}else if(data.type == 'delMember'){
					if (data.data.group_id == this.groupInfo.group_id) {
					    data.data.user_ids.forEach(member => {
					        let index = this.memberList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
					            this.memberList.splice(index, 1);
								this.memberTotal --
					        }
					    });
					}
				}else if(data.type == 'quit'){
					if (data.data.group_id == this.groupInfo.group_id) {
					    data.data.user_ids.forEach(member => {
					        let index = this.memberList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
					            this.memberList.splice(index, 1);
								this.memberTotal --
					        }
					    });
					}
				}else if(data.type == 'addMember'){
					this.getMember()
				}else if(data.type == 'managerAdd'){
					this.getMember()
				}else if(data.type == 'managerCancel'){
					this.getMember()
				}else if(data.type == 'member_nick'){
					if (data.data.group_id == this.groupInfo.group_id) {
					    let index = this.memberList.findIndex(item => item.user_id == data.data.user_id);
					    if (index !== -1) {
					        Vue.set(this.memberList[index], 'group_nickname', data.data.group_nickname);
					    }
					}
				}
			},
			async getMember(){
				try{
					let resMember = await groupMembersApi.getMemberListPage({
						group_id:this.groupInfo.group_id,
						page:1,
						limit:10
					})
					if(resMember){
						this.memberList = resMember.list
						this.memberTotal = resMember.total
					}
					console.log(resMember);
				}catch(e){
					//TODO handle the exception
				}
				
			},
			goEditInfo(){
				if(this.groupInfo.userRole == 'creator' || this.groupInfo.userRole == 'manager'){
					this.$Router.push({
						name: 'group_info_edit'
					});
				}
				
			},
			historyChat(){
				this.$Router.push({
					name: 'group_chat_history'
				});
			},
			clearchat(){
				this.$refs.clmodel.show({
					title: this.$t("my_file.setting.index.clearChatHistory"),
					content: this.$t("chat.msg.feature.chatHistory"),
					confirm: (e) => {
						e.showModel = false
						msgSqlite.clearChatHistory(this.groupInfo.group_id,'group')
					}
				})
			},
			async memberDel(item){
				uni.$u.throttle(async()=>{
					if(item.user_id == this.$store.state.user.user_info.user_id){
						return
					}
					if (!this.getPermission('can_add_friends')){
						uni.showToast({
							title:this.$t("group.group_members.memberBeingProtected"),
							icon:'none'
						})
						return
					}
					try{
						let friendRes = await uni.$api.friends.isFriend({friend_id:item.user_id})
						if(friendRes && friendRes.data.is_friend){
							this.$Router.push({
								name: 'friend_details',
								params: {
									friend_idx:item.user_id,
									avatar_url:item.avatar_url,
									nick_name:item.user_nickname,
									skipAgain:true,//再次进入聊天页面,
									groupNickname:item.group_nickname || item.user_nickname,
								}
							});
							return
						}
					}catch(e){}
					this.$Router.push({
						name: 'add_member_details',
						params: {
							user_id:item.user_id,
							nick_name:item.user_nickname,
							avatar_url:item.avatar_url,
							isGroupGo:true,
							groupNickname:item.group_nickname || item.user_nickname,
						}
					});
				}, 1000)
			},
			allMember(){
				this.$Router.push({
					name:'group_members',
					params: {
						group_id:this.groupInfo.group_id
					}
				})
			},
			
			editInfo(type,inputType,title){
				if(this.groupInfo.userRole == 'creator' || this.groupInfo.userRole == 'manager' || (inputType == 'textarea' && this.groupInfo[type])){
					let infodata = JSON.parse(JSON.stringify(this.groupInfo))
					let { avatar_url,group_name,description,notice,group_id } = infodata
					this.editInfoData = {
						type:inputType,
						title:title,
						model:type,
						data:{ avatar_url,group_name,description,notice,group_id }
					}
					if(type=='avatar_url'){
						uni.chooseImage({
							count:1,
							sourceType:['album'],
							crop: { //是否进行裁剪，此配置一般用于头像上传时裁剪成正方形等
								width: 100,
								height: 100
							},
							success: async(res) => {
							   let loadSrc = res.tempFilePaths[0];
							   try {
									let res = await upload.uploadFile(loadSrc, 'avatar', 'image')
									this.editInfoData.data.avatar_url = res.url
									this.apiUpdate()
							   } catch (e) {
							   }
							}
						})
					}else{
						this.$nextTick(()=>{
							this.$refs.clEditPop.show()
						})
					}
				}
			},
			//编辑确认
			popComplete(){
				this.apiUpdate()
			},
			
			//编辑取消
			popCancel(){
				this.editInfoData = {
					type:'',
					title:'',
					model:'',
					data:{}
				}
			},
			//修改群昵称打开
			popNameOpen(){
				this.$nextTick(()=>{
					this.$refs.clEditNamePop.show()
				})
				this.myGroupName = this.groupInfo.userNickname || this.user_info.nick_name
			},
			//修改群内昵称确认
			async popNameComplete(){
				try{
					let res = await groupMembersApi.setNickName(this.groupInfo.group_id,this.myGroupName)
					if(res){
						this.$refs.clEditNamePop.cancel()
						uni.showToast({
							title:res.msg,
							icon:'none'
						})
					}
				}catch(e){
					//TODO handle the exception
				}
				
			},
			
			//编辑取消
			popNameCancel(){
				this.myGroupName = ''
			},
			//编辑接口
			async apiUpdate(){
				let isRenewal = false
				if(this.groupInfo.avatar_url != this.editInfoData.data.avatar_url || this.groupInfo.group_name != this.editInfoData.data.group_name){
					isRenewal = true
				}
				let resapi = await groupApi.editGroupInfo(this.editInfoData.data,isRenewal)
				if(resapi){
					// this.groupInfo = Object.assign({}, this.groupInfo, this.editInfoData.data);
					this.$refs.clEditPop.cancel()
					uni.showToast({
						title:resapi.msg,
						icon:'none'
					})
				}
			},
			//获取置顶
			async gettop(){
				try{
					let Sesstion = await sqliteSeesion.getSesstionId(this.groupInfo.group_id,'is_top')
					if(Sesstion){
						this.is_top = Sesstion.is_top
					}
				}catch(e){}
			},
			//设置开关
			setChange(type,val){
				console.log(val);
				switch (type){
					case 'disturbing':
						//这里需要更新用户表和会话表
						let data = {
							disturbing: val,
						}
						this.$store.dispatch('updateSession',{
							chat_id: this.groupInfo.group_id,
							data 
						})
						sqliteGroup.editGroupInfo(this.groupInfo.group_id,data)
						//更新vuex内的信息
						this.$store.commit('updateChatGroupInfo',{
							group_id:this.groupInfo.group_id,
							disturbing: val,
						})
						break;
					case 'pinned':
						//这里只需要更新会话表
						this.$store.dispatch('updateSession',{
							chat_id: this.groupInfo.group_id,
							data: {
								is_top: val,
							}
						})
						break;
					default:
						break;
				}
			},
			//邀请好友
			invite(){
				this.$Router.push({
					name:'invite_group',
					params: {
						group_id:this.groupInfo.group_id
					}
				})
			},
			//踢人
			remove(){
				this.$Router.push({
					name:'group_members',
					params: {
						group_id:this.groupInfo.group_id,
						type:'remove'
					}
				})
			},
			//退出群聊
			async quitclick(role){
				//解散群聊
				if(role == 'creator'){
					this.$refs.clmodel.show({
						content:`${this.$t("chat.groupChatDetails.dissolveDes")}“${this.groupInfo.group_name}”`,
						confirm:async(e)=> {
							//解散群
							groupApi.dissolve(this.groupInfo.group_id)
						}
					})
					
				}else{//退出群聊
					this.$refs.clmodel.show({
						content:`${this.$t("chat.groupChatDetails.quitDes")}“${this.groupInfo.group_name}”`,
						confirm:async(e)=> {
							groupApi.memberOut(this.groupInfo.group_id)
						}
					})
				}
			},
			//不在群内删除群聊信息
			async deleteClick(){
				this.$refs.clmodel.show({
					content:`${this.$t("chat.groupChatDetails.chatHistoryDes")}`,
					confirm:async(e)=> {
						//删除会话
						await this.$store.dispatch('removeSession', this.groupInfo.group_id)
						//删除消息
						await msgSqlite.delMsgUserId(this.groupInfo.group_id,'group')
						this.$Router.back(2)
					}
				})
			},
			gopage(name){
				this.$Router.push({
					name,
					params: {
						group_id:this.groupInfo.group_id
					}
				})
			},
		},
	};
</script>

<style scoped lang="scss">
	// 样式2
	.centerTop {
		padding: 20rpx 30rpx 40rpx;
		position: relative;
		box-sizing: border-box;
		&__view{
			display: flex;
			align-items: center;
			justify-content: space-between;
			&__topview {
				display: flex;
				align-items: center;
				&__info {
					display: flex;
					flex-direction: column;
					margin-left: 30rpx;
			
					&__nickname {
						font-size: 32rpx;
						color: #FFFFFF;
					}
			
					&__account {
						font-size: 24rpx;
						color: #61626E;
					}
				}
			}
		}
		
		&__signature {
			margin-top: 40rpx;
			font-size: 28rpx;
			color: #61626E;
		}
	}
	
	.topInfo{
		background: #1E1F30;
		border-radius: 20rpx;
		margin: 20rpx 30rpx 0;
		padding: 30rpx;
		&__numview{
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			color: #FFFFFF;
			&__right{
				display: flex;
				align-items: center;
				&__num{
					font-size: 28rpx;
					color: #61626e;
				}
			}
		}
		&__view{
			display: flex;
			margin-top: 30rpx;
			gap: 10rpx;
			flex-wrap: wrap;
			&__item{
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 120rpx;
				&__nickname{
					font-size: 24rpx;
					color: #FFFFFF;
					margin-top: 20rpx;
				}
			}
			
		}
	}
	.cellviewGrop {
		background: #1E1F30;
		border-radius: 20rpx;
		margin: 20rpx 30rpx 0;
		padding: 30rpx;
		min-height: 110rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: center;
		.cellview {
			display: flex;
			justify-content: space-between;
	
			&__left {
				display: flex;
				align-items: center;
				&__title {
					font-size: 28rpx;
					color: #FFFFFF;
				}
			}
			&__right{
				display: flex;
				align-items: center;
				&__content{
					font-size: 28rpx;
					color: #61626e;
				}
			}
		}
		.cellDetails{
			font-size: 28rpx;
			color: #61626e;
			margin-top: 20rpx;
		}
	}
	.controlsBotton{
		height: 110rpx;
		text-align: center;
		line-height: 110rpx;
		background: #1E1F30;
		border-radius: 20rpx;
		margin: 20rpx 30rpx 20rpx;
		font-size: 32rpx;
		color: #FF5252;
	}
</style>